<?php 

/**
* ���������� �������� �������� �� ������� ����������
* �������� ������ � ������ ������ ��������� ���� ������� ����������
* value - ��������
* default_req - ������� ������������� ����������� ���������
* base_filter - ������ ���������
* base_validator - ��������� ���������
*
*
*/

class Zen_Controller_Action_Helper_CheckParam extends Zend_Controller_Action_Helper_Abstract{
	
		/**
		* 
		* $value - input param, can be array or value.
		*	array(
		*		'id' => array('filter' => 'Int', 'validator' => 'Int', req => 'true')
		*	)
		* 
		*/
	
		public function direct($value, $default_req = true, $base_filter = null, $base_validator = null){
			$db = Zend_Db_Table_Abstract::getDefaultAdapter();
			$f_alias = new Zen_Filter_InputParam();
			$f_xss = new Zen_Filter_XSS();
			if ( is_array($value) ) {
				$params = $value;
				$result = array();
				foreach ( $params as $key => $param ) {
					$req 		= ( isset($params[$key]['req']) ) ? $params[$key]['req'] : $default_req;
					$filter 	= ( isset($params[$key]['filter']) ) ? $params[$key]['filter'] : $base_filter;
					$validator 	= ( isset($params[$key]['validator']) ) ? $params[$key]['validator'] : $base_validator;
					$value 		= $this->checkParam($key, $req, $filter, $validator);
					$result[$key] = $f_xss->filter($f_alias->filter($db->quote($value)));
				}
			}else{
				$result = $f_xss->filter($f_alias->filter($db->quote($this->checkParam($value, $default_req, $base_filter, $base_validator))));
			}
			return $result;
		}
		
		private function checkParam($key, $req, $filter, $validator){
			if(! $this->_hasParam( $key ) && $req){
				throw new Zend_Exception("Doesn't set $key",404);		
			} elseif(! $this->_hasParam( $key )){
				$value = null;
			} else {
				$value = $this->_getParam( $key );
			}
			if (! $value && ! $req) return null;
			if ( $filter ) 
				$value = Zend_Filter::filterStatic($value, $filter);
			if (! $value && $req) {
				throw new Zend_Exception("Invalid $key",404);	
			}
			if ( $validator ) {
				if (! Zend_Validate::is($value, $validator)){
					throw new Zend_Exception("Invalid $key",404);
				}
			}
			return $value;
		}
		
		private function _hasParam($paramName)
	    {
	        return null !== $this->getRequest()->getParam($paramName);
	    }
	    
		protected function _getParam($paramName, $default = null)
	    {
	        $value = $this->getRequest()->getParam($paramName);
	         if ((null === $value || '' === $value) && (null !== $default)) {
	            $value = $default;
	        }
	
	        return $value;
	    }
}